// 调试键盘模拟问题
const { exec } = require('child_process');
const { promisify } = require('util');

const execAsync = promisify(exec);

async function debugKeyboard() {
  console.log('========================================');
  console.log('键盘模拟调试工具');
  console.log('========================================\n');

  // 测试1: 检查PowerShell执行策略
  console.log('测试1: 检查PowerShell执行策略');
  try {
    const { stdout } = await execAsync('powershell -Command "Get-ExecutionPolicy"');
    console.log(`执行策略: ${stdout.trim()}`);
    
    if (stdout.trim() === 'Restricted') {
      console.log('⚠️ 执行策略受限，可能影响键盘模拟');
      console.log('建议运行: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser');
    } else {
      console.log('✓ 执行策略正常');
    }
  } catch (error) {
    console.log('✗ 检查执行策略失败:', error.message);
  }
  console.log('');

  // 测试2: 检查PowerPoint进程
  console.log('测试2: 检查PowerPoint进程');
  try {
    const { stdout } = await execAsync('powershell -Command "Get-Process | Where-Object {$_.ProcessName -eq \'POWERPNT\'} | Format-Table ProcessName, MainWindowTitle -AutoSize"');
    
    if (stdout.trim().length > 0) {
      console.log('✓ PowerPoint进程信息:');
      console.log(stdout);
    } else {
      console.log('✗ 未找到PowerPoint进程');
      console.log('请确保PowerPoint已打开');
    }
  } catch (error) {
    console.log('✗ 检查PowerPoint进程失败:', error.message);
  }
  console.log('');

  // 测试3: 测试基本的SendKeys功能
  console.log('测试3: 测试基本SendKeys功能');
  try {
    console.log('尝试发送一个简单的按键（空格键）...');
    
    const psScript = `
      Add-Type -AssemblyName System.Windows.Forms
      Write-Host "准备发送空格键..."
      [System.Windows.Forms.SendKeys]::SendWait(" ")
      Write-Host "空格键已发送"
    `;

    const { stdout, stderr } = await execAsync(`powershell -Command "${psScript}"`, {
      timeout: 3000
    });

    console.log('PowerShell输出:', stdout);
    if (stderr) {
      console.log('PowerShell错误:', stderr);
    }
    console.log('✓ SendKeys基本功能测试完成');
  } catch (error) {
    console.log('✗ SendKeys测试失败:', error.message);
  }
  console.log('');

  // 测试4: 测试箭头键发送
  console.log('测试4: 测试箭头键发送');
  try {
    console.log('等待5秒，请确保PowerPoint窗口在前台...');
    await sleep(5000);
    
    console.log('发送右箭头键...');
    
    const psScript = `
      Add-Type -AssemblyName System.Windows.Forms
      Write-Host "发送右箭头键..."
      [System.Windows.Forms.SendKeys]::SendWait("{RIGHT}")
      Write-Host "右箭头键已发送"
    `;

    const { stdout, stderr } = await execAsync(`powershell -Command "${psScript}"`, {
      timeout: 3000
    });

    console.log('PowerShell输出:', stdout);
    if (stderr) {
      console.log('PowerShell错误:', stderr);
    }
    console.log('✓ 箭头键发送完成');
    
    console.log('等待2秒后发送左箭头键...');
    await sleep(2000);
    
    const psScript2 = `
      Add-Type -AssemblyName System.Windows.Forms
      Write-Host "发送左箭头键..."
      [System.Windows.Forms.SendKeys]::SendWait("{LEFT}")
      Write-Host "左箭头键已发送"
    `;

    const { stdout: stdout2, stderr: stderr2 } = await execAsync(`powershell -Command "${psScript2}"`, {
      timeout: 3000
    });

    console.log('PowerShell输出:', stdout2);
    if (stderr2) {
      console.log('PowerShell错误:', stderr2);
    }
    console.log('✓ 左箭头键发送完成');
    
  } catch (error) {
    console.log('✗ 箭头键测试失败:', error.message);
  }
  console.log('');

  // 测试5: 测试窗口激活
  console.log('测试5: 测试PowerPoint窗口激活');
  try {
    const psScript = `
      Add-Type -AssemblyName System.Windows.Forms
      $pptProcess = Get-Process | Where-Object {$_.MainWindowTitle -like "*PowerPoint*"} | Select-Object -First 1
      if ($pptProcess) {
        Write-Host "找到PowerPoint窗口: $($pptProcess.MainWindowTitle)"
        $sig = '[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);'
        $type = Add-Type -MemberDefinition $sig -Name WindowAPI -PassThru
        $result = $type::SetForegroundWindow($pptProcess.MainWindowHandle)
        Write-Host "窗口激活结果: $result"
      } else {
        Write-Host "未找到PowerPoint窗口"
      }
    `;

    const { stdout, stderr } = await execAsync(`powershell -Command "${psScript}"`, {
      timeout: 3000
    });

    console.log('PowerShell输出:', stdout);
    if (stderr) {
      console.log('PowerShell错误:', stderr);
    }
  } catch (error) {
    console.log('✗ 窗口激活测试失败:', error.message);
  }
  console.log('');

  // 测试6: 使用我们的KeyboardController
  console.log('测试6: 使用KeyboardController类');
  try {
    const KeyboardController = require('./src/KeyboardController');
    const keyboard = new KeyboardController();
    
    console.log('检查PowerPoint是否运行...');
    const isRunning = await keyboard.isPowerPointRunning();
    console.log(`PowerPoint运行状态: ${isRunning}`);
    
    if (isRunning) {
      console.log('尝试激活PowerPoint窗口...');
      const focused = await keyboard.focusPowerPoint();
      console.log(`窗口激活结果: ${focused}`);
      
      console.log('等待3秒后发送按键...');
      await sleep(3000);
      
      console.log('发送右箭头键...');
      const result1 = await keyboard.sendKey('right');
      console.log(`发送结果: ${result1}`);
      
      await sleep(2000);
      
      console.log('发送左箭头键...');
      const result2 = await keyboard.sendKey('left');
      console.log(`发送结果: ${result2}`);
    }
  } catch (error) {
    console.log('✗ KeyboardController测试失败:', error.message);
  }

  console.log('\n========================================');
  console.log('调试完成');
  console.log('========================================');
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

debugKeyboard().catch(error => {
  console.error('调试过程中发生错误:', error);
  process.exit(1);
});